package com.lqd.mall.sso.controller;

import com.lqd.mall.basis.response.CommonResult;
import com.lqd.mall.basis.response.Result;
import com.lqd.mall.basis.utils.JwtUtils;
import com.lqd.mall.basis.utils.StringUtils;
import com.lqd.mall.interaction.sso.vo.LoginVo;
import com.lqd.mall.interaction.system.vo.LoginUserVo;
import com.lqd.mall.security.auth.AuthUtil;
import com.lqd.mall.security.service.TokenService;
import com.lqd.mall.security.utils.SecurityUtils;
import com.lqd.mall.sso.AuthControllerApi;
import com.lqd.mall.sso.service.ISysLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 零起点
 * @create 2022-02-13 9:36
 */
@RestController
public class AuthController implements AuthControllerApi {

    @Autowired
    ISysLoginService sysLoginService;

    @Autowired
    private TokenService tokenService;

    @Override
    public Result<Map<String,Object>> login(LoginVo loginVo) {
        LoginUserVo login = sysLoginService.login(loginVo);
        return Result.SUCCESS(tokenService.createToken(login));
    }

    @Override
    public CommonResult logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if(StringUtils.isNotEmpty(token)){
            String name = JwtUtils.getUserName(token);
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(name);
        }

        return CommonResult.SUCCESS();
    }

    @Override
    public CommonResult refresh(HttpServletRequest request)
    {
        LoginUserVo loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return CommonResult.SUCCESS();
        }
        return CommonResult.SUCCESS();
    }
}
